# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/14'
__author__ = 'Just'
__filename__ = 'error'
"""
import json
from flask import request
from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    """API异常基类"""
    code = 500
    msg = '服务器有一个异常'
    error_code = 999

    def __init__(self, code=None, msg=None, error_code=None, headers=None):
        if msg:
            self.msg = msg
        if code:
            if isinstance(code, int):
                self.code = code
            else:
                raise UnicodeEncodeError()
        if error_code:
            self.error_code = error_code
        super(APIException, self).__init__(msg, None)

    def get_body(self, environ=None):
        """重写 body 形式"""
        body = dict(
            msg=self.msg,
            error_code=self.error_code,
            request=request.method + ' ' + self.get_url_no_param()
        )
        text = json.dumps(body)  # 字典转文本
        return text

    def get_headers(self, environ=None):
        """重写 header 返回格式"""
        return [("Content-Type", "application/json")]

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]
